
#include "channels_manager.hpp"
#include "messages_channels.hpp"
#include "channels_observers_container.hpp"

namespace fasys{

struct f_fire
{
  const message& _message;
  f_fire(const message& m): _message(m) {}
  void operator()(const channels_observer_info& coi)
  {
    coi.observer->publish(_message);
  }
};

channels_manager::~channels_manager()
{
  delete _messages_channels;
  delete _observers;
}

channels_manager::channels_manager()
  : _messages_channels(new messages_channels)
  , _observers(new channels_observers_container)
{
}

void channels_manager::publish(message& m)
{
  std::cout << "void channels_manager::publish(message& m): "<< m.channel << std::endl;
  _messages_channels->publish(m);
  std::cout << "\tchannel_id="<<m.channel_id << std::endl;
  _observers->fire(m.channel_id, f_fire(m) );
}

void channels_manager::subscribe( const std::string& channel, ichannel_observer* obs)
{
  std::cout << "void channels_manager::subscribe( const std::string& channel, ichannels_observer* obs): "<< channel << std::endl;
  channel_id_t channel_id = _messages_channels->create(channel);
  std::cout << "\tchannel_id="<<channel_id << std::endl; 
  _observers->subscribe(channel_id, obs);
}

void channels_manager::describe( const std::string& channel, ichannel_observer* obs)
{
  channel_id_t channel_id = _messages_channels->create(channel);
  _observers->describe(channel_id, obs);
}

void channels_manager::describe( ichannel_observer* obs)
{
  _observers->describe(obs);
}

}